import { IncomingMessage, ServerResponse } from "http";
import { AccountModel } from "../account_server/model/AccountModel";
import { UserDao } from "../account_server/dao/UserDao";
import { HallServer_SocketMsgHandler } from "../hall_server/HallServer_SocketMsgHandler";
import { Config } from "../src/config/Config";
import { ErrorCode } from "../src/config/ErrorCode";
import { ServerConfig } from "../src/config/ServerConfig";
import DateUtil from "../src/engine/utils/DateUtil";
import { HaoEncrypt } from "../src/engine/utils/HaoEncrypt";
import { Logger } from "../src/engine/utils/Logger";
import { Md5Helper } from "../src/engine/utils/Md5Helper";
import { WebUtil } from "../src/engine/utils/WebUtil";
import { GameImgHelper } from "../src/game/helper/GameImgHelper";
import { ResponseModel } from "../src/model/ResponseModel";
import { ServerManager } from "../src/server/ServerManager";
const request = require('request');
const crypto = require("crypto");
const multer = require('multer');

const routerMap = {
    updateServerStatus: "/updateServerStatus",
    upload_img: "/upload_img", //上传图片
}

export class UploadReqHandler {

    public static instance: UploadReqHandler = new UploadReqHandler();

    //     private versionStr: string =
    //         `
    //     {
    //         "iv": "1.0.0.100",
    //         "av": "1.0.0.101",
    //         "al": "http://ibirdgame.cn:9604/202109245.apk",
    //         "il": "http://ibirdgame.cn:9604/202109245.apk"
    //     }
    // `

    public init(app) {
        for (const key in routerMap) {
            if (routerMap[key] == routerMap.upload_img) {
                app.post(routerMap.upload_img, multer().single('file'), this.on_upload_img.bind(this));
            } else {
                app.use(routerMap[key], this.onBaseRoot.bind(this))
            }
        }
    }

    private onBaseRoot(req, resp) {
        try {
            let ip: string = WebUtil.getIpByExpressReq(req);
            Logger.log("onBaseRoot=req=", ip, req.baseUrl)
            if (req.baseUrl == routerMap.updateServerStatus) {
                ServerConfig.initConfig(ServerConfig.nowServerConfig.nowPort)
                resp.end("success");
            }
        } catch (error) {
            Logger.warn("onBaseRoot error", error);
        }
    }

    private checkBody(ip: string, req, resp, callback: Function) {
        if (req.body) {
            try {
                let jsonObj = JSON.parse(req.body);
                let k: string = jsonObj["k"];
                let data: object = jsonObj["data"]
                if (k == Md5Helper.getMd5_encrypt(JSON.stringify(data))) {
                    callback && callback(req, resp, data, ip);
                }
                else {
                    Logger.warn("收到非法Http请求 key", ip, req.body)
                    resp.end();
                }
            } catch (error) {
                Logger.warn("收到非法Http请求body", ip, req.body, error)
                resp.end();
            }
        }
        else {
            resp.end();
        }
    }

    private async on_upload_img(req, resp) {
        let ip: string = WebUtil.getIpByExpressReq(req);
        let k: string = req.body["k"]
        let data: string = req.body["data"]
        Logger.log("on_upload_img==ip=", ip, k, data)
        let respModel: ResponseModel = new ResponseModel()
        if (k == Md5Helper.getMd5_encrypt(data)) {
            respModel.code = ErrorCode.Code.Suc
            try {
                let dataObj: object = JSON.parse(data)
                let userid: number = dataObj["userid"]
                let uploadType: number = dataObj["uploadType"]
                let sign: string = dataObj["sign"]
                let account: string = dataObj["account"]
                if (req.file) {
                    let respModel = await AccountModel.login_async(account, sign)

                    // Logger.warn("on_upload_img==ip=====111=", userid, account,  sign)

                    if (respModel.code == ErrorCode.Code.Suc) {
                        let userData: object = await UserDao.get_user_data_by_account(account)
                        // Logger.warn("on_upload_img==ip=====2222=", userid, account,  sign)
                        if (userData) {
                            // Logger.warn("on_upload_img==ip=====44444=",data, userid)
                            if (userid == userData["userid"]) {
                                let buffer = req.file.buffer;
                                let imgurl: string = GameImgHelper.buffer_to_imgurl(userid, uploadType, buffer)
                                // respModel = await HallServer_SocketMsgHandler.saveUploadImg(imgurl, uploadType, userid, data["login_type"])
                                // Logger.warn("on_upload_img==ip=====5555=",data, userid)
                                if (respModel.code == ErrorCode.Code.Suc) {
                                    ServerManager.instance.notify_update_img(userid, imgurl, uploadType)
                                }
                            } else {
                                respModel.code = ErrorCode.Code.Fail
                                respModel.msg = "用户id不对"
                            }
                        }
                        else {
                            respModel.code = ErrorCode.Code.Fail
                            respModel.msg = "账号玩家不存在"
                        }
                        resp.end(JSON.stringify(respModel))
                    } else {
                        resp.end(JSON.stringify(respModel))
                    }
                }
                else {
                    respModel.code = ErrorCode.Code.Fail
                    respModel.msg = "on_upload_img==上传文件不存在"
                    resp.end(JSON.stringify(respModel))
                }
            } catch (error) {
                Logger.warn("error==", error)
                respModel.code = ErrorCode.Code.Fail
                respModel.msg = "data不是json"
                resp.end(JSON.stringify(respModel))
            }

        } else {
            respModel.code = ErrorCode.Code.Fail
            respModel.msg = "签名错误"
            resp.end(JSON.stringify(respModel))
        }

    }


}